package gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;

import model.User;

/**
 * 
 * @author Ahmed Abdul-Rahman(aabdulr@gmail.com)
 * @author jpgunter - Implemented mouse listener.
 * @version Winter 2012.
 * 
 */
public class VolunteerListView extends JPanel implements ActionListener {

  public static int PREFFERED_HEIGHT = 400;
  public static int PREFFERED_WIDTH = 800;

  private JTable my_table;
  private String[][] my_table_data;

  private MainWindow my_parent;
  private JButton my_back_button;
  private JButton my_home_button;

  /**
   * Creates the panel.
   * 
   * @param the_parent
   * @param the_users
   */
  public VolunteerListView(MainWindow the_parent, final List<User> the_users) {

    my_parent = the_parent;

    setPreferredSize(new Dimension(PREFFERED_WIDTH, PREFFERED_HEIGHT));

    setLayout(new BorderLayout());

    JPanel header_panel = new JPanel(new BorderLayout());
    JLabel lblVolunteers = new JLabel("Volunteers (Click to View Details)");
    lblVolunteers.setHorizontalAlignment(SwingConstants.CENTER);
    header_panel.add(lblVolunteers, BorderLayout.CENTER);

    my_back_button = new JButton("Back");
    my_back_button.addActionListener(this);
    header_panel.add(my_back_button, BorderLayout.WEST);

    my_home_button = new JButton("Home");
    my_home_button.addActionListener(this);
    header_panel.add(my_home_button, BorderLayout.EAST);

    add(header_panel, BorderLayout.NORTH);

    JScrollPane scrollPane = new JScrollPane();
    add(scrollPane, BorderLayout.CENTER);

    String[] table_headers = new String[] { "Name", "Email"};

    my_table_data = new String[the_users.size()][2];

    for (int i = 0; i < the_users.size(); i++) {
      my_table_data[i][0] = the_users.get(i).getUserName();
      my_table_data[i][1] = the_users.get(i).getUserEmail();
    }

    my_table = new JTable();
    my_table.setModel(new DefaultTableModel(my_table_data, table_headers));


    scrollPane.setViewportView(my_table);

    my_table.addMouseListener(new MouseAdapter() {

      @Override
      public void mouseClicked(MouseEvent the_event) {
        my_parent.showVolunteer(the_users.get(my_table.getSelectedRow()));
      }
    });
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == my_back_button) {
      my_parent.back();
    } else if (e.getSource() == my_home_button) {
      my_parent.home();
    }

  }
}
